import React, { useEffect, useMemo, useRef, useState } from "react";
import dynamic from "next/dynamic";
import { Button, Checkbox, Form, Input, Select, Switch, message } from "antd";
import { PrismaClient } from "@prisma/client";
import { useRouter } from "next/router";
import "suneditor/dist/css/suneditor.min.css";
import { useDeviceMode } from "@/hooks/useDeviceMode";
import Head from "next/head";

// import MyEditor from '@/components/MyEditor';

type Tag = { name: string; id: number };
interface WritePageProps {
  tags: Tag[];
  articleData: FormData;
}
type FormData = {
  title: string;
  content?: string;
  id?: string;
  public: boolean;
} & Pick<WritePageProps, "tags">;
const STORAGE_KEY = "__WRITE_CACHE__";

// const SunEditor = dynamic(
//   import("suneditor-react").then((d) => d.default),
//   {
//     loading: () => <p>Loading...</p>,
//     ssr: false,
//   },
// );

const RichEditor = dynamic(
  import("@/components/MyEditor").then((d) => d.default),
  {
    loading: () => <p>正在加载富文本</p>,
    ssr: false,
  },
);

const WritePage = (props: WritePageProps) => {
  const mobile = useDeviceMode();
  const router = useRouter();
  const formRef = useRef(null);
  const [msgApi, msgCtx] = message.useMessage();

  const [html, setHtml] = useState("");
  const [textLength, setTextLength] = useState(0);

  /**@description 加载缓存数据 */
  useEffect(() => {
    const cache = localStorage.getItem(STORAGE_KEY);
    cache && setHtml(cache);
  }, []);

  async function onFormFinished(form: FormData) {
    console.log("html", html, textLength);
    if (textLength < 1) {
      msgApi.warning("还没有输入内容");
      return;
    } else {
      form.content = html;
    }
    const r = await fetch("/api/save-article", {
      method: "POST",
      body: JSON.stringify({
        ...form,
        id: props.articleData?.id || undefined,
      }),
    });
    await r.json();
    localStorage.removeItem(STORAGE_KEY);
    msgApi.success("保存成功");
    router.push("/");
  }

  const tagOptions = useMemo(() => {
    return props.tags.map((o) => ({ label: o.name, value: o.id }));
  }, [props.tags]);

  const saveDraftWhenChange = (content: string) => {
    localStorage.setItem(STORAGE_KEY, content);
  };

  // const dynamicButtonList = useMemo(() => {
  //   return mobile
  //     ? [
  //         ["undo", "redo"],
  //         ["link", "image"],
  //         ["bold", "underline", "italic", "removeFormat"],
  //       ]
  //     : [
  //         ["undo", "redo"],
  //         ["font", "fontSize", "formatBlock"],
  //         ["bold", "underline", "italic", "strike", "subscript", "superscript"],
  //         ["fontColor", "hiliteColor", "textStyle"],
  //         ["removeFormat"],
  //         "/", // 分隔线
  //         ["outdent", "indent"],
  //         ["align", "horizontalRule", "list", "lineHeight"],
  //         ["table", "link", "image"],
  //         ["fullScreen", "codeView"],
  //       ];
  // }, [mobile]);

  return (
    <>
      {msgCtx}
      <Head>
        <title>写一篇文章</title>
      </Head>
      <div className="p-10 box-border">
        <Form ref={formRef} style={{ width: "100%" }} onFinish={onFormFinished}>
          <Form.Item
            name="title"
            required
            rules={[{ required: true, message: "请输入标题" }]}
          >
            <Input placeholder="标题"></Input>
          </Form.Item>
          <Form.Item name="tags">
            <Select
              mode="multiple"
              placeholder="添加一些标签"
              allowClear
              options={tagOptions}
            />
          </Form.Item>
          <Form.Item>
            {/* <SunEditor
              getSunEditorInstance={getSunInstance}
              onChange={saveDraftWhenChange}
              lang={"zh_cn"}
              height="50vh"
              setOptions={{
                buttonList: dynamicButtonList,
              }}
            /> */}

            <RichEditor
              html={html}
              setHtml={setHtml}
              onChangeEffect={saveDraftWhenChange}
              setTextLength={setTextLength}
            ></RichEditor>
          </Form.Item>
          <Form.Item
            name="public"
            valuePropName="checked"
            label="公开"
            labelAlign="left"
          >
            <Switch></Switch>
          </Form.Item>
          <Form.Item className="text-right">
            <Button htmlType="submit" type="primary">
              {props.articleData ? "更新文章" : "确认发布"}
            </Button>
          </Form.Item>
        </Form>
      </div>
    </>
  );
};

export async function getServerSideProps({
  query,
}: {
  query: { id?: string };
}) {
  const prisma = new PrismaClient();

  const tags = await prisma.tags.findMany({
    select: {
      id: true,
      name: true,
    },
  });
  let articleData: FormData | null = null;
  if (query.id) {
    articleData = await prisma.article.findUnique({
      where: {
        id: query.id,
      },
      select: {
        id: true,
        title: true,
        content: true,
        public: true,
        tags: {
          select: {
            id: true,
            name: true,
          },
        },
      },
    });
  }

  return {
    props: {
      tags: tags,
      articleData,
    },
  };
}

export default WritePage;
